package net.hserver.apm.service;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import net.hserver.apm.common.entity.ServerInfo;
import net.hserver.apm.config.MongodbConfig;
import org.bson.Document;
import org.bson.conversions.Bson;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Bean
public class ServerInfoService {

    @Autowired
    private MongoClient mongoClient;

    public Object getServerInfo() {
        Map<String, List<Document>> map = new HashMap<>();
        /**
         * 获取有哪些服务
         */
        MongoDatabase database = mongoClient.getDatabase(MongodbConfig.DATA_BASE);
        MongoCollection<Document> server_info = database.getCollection("serverInfo");
        DistinctIterable<String> appName1 = server_info.distinct("appName", String.class);
        /**
         * 获取每个服务的信息
         */
        //今天
        long start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toEpochSecond(ZoneOffset.of("+8")) * 1000;
        long end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).toEpochSecond(ZoneOffset.of("+8")) * 1000;
        Bson bson = BasicDBObject.parse("{\"time\":{\"$gte\":" + start + ",\"$lte\":" + end + "}}");
        for (String appName : appName1) {
            Bson appNameBson = Filters.and(Filters.eq("appName", appName), bson);
            MongoCursor<Document> iterator = server_info.find(appNameBson).iterator();
            try {
                List<Document> data = new ArrayList<>();
                while (iterator.hasNext()) {
                    data.add(iterator.next());
                }
                map.put(appName, data);
            }finally {
                iterator.close();
            }
        }
        return map;
    }
}
